#!/bin/bash
# Author: Narunas Krasauskas
# Purpose: Helper script to run various instances of kvm-qemu images
# Tested On: Debian GNU/Linux 6.0.7 (squeeze) x86_64
# Version: 1a
# Time: 2013/11/24
# Copyright: GPLv3
# Use with caution! Author doesn't take any responsibility for any damage
# caused using these scripts.

## Variables
_IMG="$1"
_ifup="/etc/qemu-ifup"
_ifdown="/etc/qemu-ifdown"
_log="./"

## Check user space variable sanity
if [ ! -f "$_IMG" ]; then
	echo 'Watch out! No image file specified.'
	echo "Usage: ./`basename $0` path_to_img_file"
	exit 1
fi

## Initialize and increment required variables
function iivar()
{
	# Check tun/tap interface availability
	if ip link show | grep -q 'tap'; then
		# Increment index if interfaces are present
		_n=$(ip link show | grep -Eo 'tap[0-9]{1,2}' | sort -V | tail -n1 | grep -Eo '[0-9]{1,2}')
		_n=$(($_n+1))
		_tap="kvm-tap$_n"
		# Set vlan accordingly
		_vlan="$_n"
	else
		_tap="kvm-tap0"
		_vlan="0"
	fi
	# Create fictitious mac address
	if test "$_n" -gt 99; then
		echo "Too many Virtual Machines!!"
		exit 1
	else
		_mac="52:54:00:12:34:$(printf %02d $_n)"
	fi
	# Check vnc availability
	_n=$(netstat -ntlp | grep kvm | grep -Eo ':59[0-9]{2}' | tail -c2)
	if ! test -z $_n; then
		# Increment index if screens are present
		_vnc=$(($_n+1))
	else
		_vnc=1
	fi
}
## Initialize variables immediately afterwards definition
iivar

ARGS="-hda $_IMG -boot c -m 256 -vnc :$_vnc -net nic,vlan=$_vlan,macaddr=$_mac -net tap,vlan=$_vlan,ifname=$_tap,script=no,downscript=$_ifdown -localtime -k en-gb -enable-kvm"

echo -e "\n1] Loading \"kvm_intel\" kernel module..."
if ! lsmod | grep -q "kvm_intel"; then
	modprobe "kvm_intel" && sleep 1
fi

echo -e "\n2] Initializing network devices...\n"
source $_ifup $_tap

echo -e "\n3] Starting QEMU with the following configuration:" | tee -a $_log/kvm-stats.txt
echo "* VM Image ...... : $_IMG" 	| tee -a $_log/kvm-stats.txt
echo "* Tun/Tap ....... : $_tap" 	| tee -a $_log/kvm-stats.txt
echo "* VLAN .......... : $_vlan"	| tee -a $_log/kvm-stats.txt
echo "* MAC ........... : $_mac" 	| tee -a $_log/kvm-stats.txt
echo "* VNC Screen .... : $_vnc" 	| tee -a $_log/kvm-stats.txt
echo -ne "\nFull param-set: " 		| tee -a $_log/kvm-stats.txt
echo -e "$ARGS\n" 			| tee -a $_log/kvm-stats.txt
kvm $ARGS &
